/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ContentManagers.Servlets;

import ContentManagers.Models.Attempt;
import ContentManagers.RoleManagers.AttemptManager;
import ContentManagers.Models.Customer;
import ContentManagers.RoleManagers.CustomerManager;
import ContentManagers.RoleManagers.CustomerSessionManager;
import ContentManagers.Security.Validator;
import ContentManagers.Security.WebLogger;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.sql.ResultSet;
import java.sql.Timestamp;

/**
 *
 * @author Martin San Diego
 */
public class ServletCustomerLogin extends HttpServlet {

   protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            int attemptCnt = 1;
            
            resetIfTimeOut(request); 
            //reset attemptCount timeouts after 5 minutes
            attemptCnt = new AttemptManager().latestAttemptCount(request.getParameter("username"), request.getRemoteAddr().toString());
            //check if attemptCount = 5
            
            if(attemptCnt < 5) //proceed to checking user credentials if attemptCount < 5
            {   
                boolean checker, logAttempt = false;
            
                Customer loginCustomer = new Customer();
                loginCustomer.setUsername(request.getParameter("username"));
                loginCustomer.setPassword(request.getParameter("password"));
            
                checker = new CustomerManager().checkCustomer(loginCustomer);
            
                    if (checker) //if credentials are in DB, proceed to generating unique session variable
                    {
                        WebLogger.insertLog(request.getRemoteAddr().toString(),request.getHeader("referer"),request.getRequestURI().toString(),"Customer "+loginCustomer.getUsername()+" authentication successful.",true); 
                        //renew session
                        boolean sessionRenew = new CustomerSessionManager().deleteCustomerSession(request.getParameter("username"));
                        request.getSession().invalidate();
                        
                        String newSessionID;

                        HttpSession session = request.getSession();
                        session.setAttribute("username", loginCustomer.getUsername());

                        //unique session generation here
                        newSessionID = new CustomerSessionManager().createCustomerSession(request.getParameter("username"), request.getRemoteAddr());
                        session.setAttribute("sessionID", newSessionID);
                        
                        //reset attemptCount in DB once user has gained access
                        checker = new AttemptManager().clearAttemptCount(request.getParameter("username"), request.getRemoteAddr().toString());
                        session.setAttribute("formLockout", "off");
                       
                        response.sendRedirect("user_index.jsp");
                    } 
                    else 
                    {
                        WebLogger.insertLog(request.getRemoteAddr().toString(),request.getHeader("referer"),request.getRequestURI().toString(),"Customer "+loginCustomer.getUsername()+" authentication failed.",false); 
                        HttpSession session = request.getSession();
                        session.setAttribute("errorMessage","invalid");
                        //this section is for the LockOut mechanism. Counting from 1 to 5.
                        lockOutMechanism(attemptCnt, request, response);

                     }
            }
                else
                lockOutMechanism(attemptCnt, request, response);
            
        } finally {            
            out.close();
        }
    }
   
   public static void resetIfTimeOut(HttpServletRequest request)
   {
       boolean clear = new AttemptManager().checkTimeStamp();
       if(true == clear)
       {
           HttpSession session = request.getSession();
           session.setAttribute("formLockout", "off");                       
       }
       
   }
   
   public void lockOutMechanism(int attemptCnt, HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
   {    
       
       boolean checker, logAttempt = false;
       
        checker = new AttemptManager().checkIfAlreadyExists(request.getParameter("username"));

                        if(checker == false)   
                        {   Attempt newAttempt = new Attempt();
                            newAttempt.setUsername(request.getParameter("username"));
                            newAttempt.setAttemptCount(attemptCnt);
                            newAttempt.setFromIP(request.getRemoteAddr());
                            logAttempt = new AttemptManager().addAttemptRecord(newAttempt);
                            //System.out.print("umabot ako dito");
                        }
                        else
                        {   
                            if(attemptCnt < 3)
                            {
                                java.util.Date date= new java.util.Date();
                                checker = new AttemptManager().addAttemptCount(request.getParameter("username"), attemptCnt++, (new Timestamp(date.getTime())).toString(), request.getRemoteAddr().toString());
                                //System.out.print("dito rin");
                            }
                            else if(attemptCnt == 3)
                            {
                                HttpSession session = request.getSession();
                                session.setAttribute("formLockout", "on");
                                
                                //ResultSet usernames = new AttemptManager().getUsernamesToLock(request.getRemoteAddr().toString());
                                
                                //System.out.print(session.getAttribute("formLockout") + "dito rin rin");
                            }
                            
                        }
                        response.sendRedirect("index_new_user.jsp");
   }
   
  
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
